/*==============================================================================
案例10：企业管理综合评价 - 熵权TOPSIS方法
==============================================================================
作者：张立强
日期：2025-11-07
版本：2.0 (改进版)

改进内容：
1. 增加数据质量检查（缺失值、异常值检测）
2. 增加指标相关性分析
3. 增加敏感性分析
4. 改进输出格式和报告
5. 增加更详细的统计分析
6. 优化可视化效果
==============================================================================*/

clear all
set more off
set seed 12345

* 创建输出目录
capture mkdir "output"
capture mkdir "output/cases"
capture mkdir "output/cases/figures"
capture mkdir "data/cases"

* 开启日志记录
capture log close
log using "output/cases/case10_entropy_topsis_evaluation.log", replace text

display "================================================================================"
display "企业管理综合评价 - 熵权TOPSIS方法"
display "================================================================================"
display "开始时间: " c(current_date) " " c(current_time)
display ""

/*------------------------------------------------------------------------------
第一部分：数据加载和数据质量检查
------------------------------------------------------------------------------*/

display "第一部分：数据加载和数据质量检查"
display "--------------------------------------------------------------------------------"

* 加载数据
use "data/enterprise_evaluation.dta", clear

* 显示数据结构
describe

* 定义指标变量
local indicators "profit growth efficiency innovation risk satisfaction"
local n_indicators: word count `indicators'
local n_companies = _N

display ""
display "数据概况："
display "- 企业数量: `n_companies'"
display "- 指标数量: `n_indicators'"
display ""

* 1.1 缺失值检查
display "1.1 缺失值检查："
misstable summarize `indicators'
local has_missing = 0
foreach var of local indicators {
    qui count if missing(`var')
    if r(N) > 0 {
        display "  警告: `var' 存在 " r(N) " 个缺失值"
        local has_missing = 1
    }
}
if `has_missing' == 0 {
    display "  ✓ 所有指标无缺失值"
}
display ""

* 1.2 描述性统计
display "1.2 描述性统计："
summarize `indicators', detail

* 1.3 异常值检测（使用3σ原则和箱线图法）
display ""
display "1.3 异常值检测（3σ原则）："
foreach var of local indicators {
    qui summarize `var'
    local mean = r(mean)
    local sd = r(sd)
    local lower = `mean' - 3*`sd'
    local upper = `mean' + 3*`sd'

    qui count if `var' < `lower' | `var' > `upper'
    if r(N) > 0 {
        display "  警告: `var' 存在 " r(N) " 个异常值（超出3σ范围）"
    }
    else {
        display "  ✓ `var' 无异常值"
    }
}
display ""

* 1.4 指标相关性分析
display "1.4 指标相关性分析："
display "  检查指标间的独立性（相关系数>0.8可能存在多重共线性）"
pwcorr `indicators', star(0.05)
display ""

* 显示原始数据
display "原始数据："
list company profit growth efficiency innovation risk satisfaction, clean noobs separator(0)

/*------------------------------------------------------------------------------
第二部分：数据标准化
------------------------------------------------------------------------------*/

display ""
display "第二部分：数据标准化"
display "--------------------------------------------------------------------------------"

* 数据标准化（向量标准化）
display "使用向量标准化方法："
display "  公式: x_ij* = x_ij / sqrt(Σx_ij²)"
display ""

foreach var of local indicators {
    * 计算每个指标的平方和
    qui gen `var'_sq = `var'^2
    qui egen `var'_sum_sq = total(`var'_sq)
    qui gen `var'_norm = `var' / sqrt(`var'_sum_sq)
    drop `var'_sq `var'_sum_sq
    label variable `var'_norm "`var'(标准化)"
}

* 验证标准化结果（每列平方和应为1）
display "标准化验证（每列平方和应为1）："
foreach var of local indicators {
    qui gen `var'_sq_check = `var'_norm^2
    qui egen `var'_sum_check = total(`var'_sq_check)
    local sum_val = `var'_sum_check[1]
    display "  `var': " %8.6f `sum_val'
    drop `var'_sq_check `var'_sum_check
}
display ""

* 显示标准化后的数据
display "标准化后的数据："
list company profit_norm growth_norm efficiency_norm innovation_norm risk_norm satisfaction_norm, clean noobs separator(0)

/*------------------------------------------------------------------------------
第三部分：计算熵权
------------------------------------------------------------------------------*/

display ""
display "第三部分：计算熵权"
display "--------------------------------------------------------------------------------"

* 3.1 计算标准化值的比重
display "3.1 计算指标比重 p_ij = x_ij* / Σx_ij*"
foreach var of local indicators {
    qui egen `var'_sum = total(`var'_norm)
    qui gen `var'_weight = `var'_norm / `var'_sum
    drop `var'_sum
    label variable `var'_weight "`var'(比重)"
}

* 3.2 计算信息熵
display "3.2 计算信息熵 E_j = -k * Σ(p_ij * ln(p_ij))"
display "    其中 k = 1/ln(m), m为企业数量"
local k_value = 1 / ln(`n_companies')
display "    k = " %8.6f `k_value'
display ""

foreach var of local indicators {
    qui gen `var'_ln = ln(`var'_weight) if `var'_weight > 0
    qui replace `var'_ln = 0 if `var'_weight == 0
    qui gen `var'_entropy = -(`var'_weight * `var'_ln)
    qui egen `var'_entropy_sum = total(`var'_entropy)
    qui gen `var'_k = 1 / ln(`n_companies')
    qui gen `var'_e = `var'_k * `var'_entropy_sum
    drop `var'_ln `var'_entropy `var'_entropy_sum `var'_k
    label variable `var'_e "`var'(熵值)"
}

* 3.3 计算差异系数和权重
display "3.3 计算差异系数 D_j = 1 - E_j"
display "3.4 计算权重 W_j = D_j / ΣD_j"
display ""

foreach var of local indicators {
    qui gen `var'_d = 1 - `var'_e
    qui egen `var'_d_sum = total(`var'_d)
    qui gen `var'_w = `var'_d / `var'_d_sum
    drop `var'_d_sum
    label variable `var'_w "`var'(权重)"
}

* 提取权重值（只保留第一行的值）
foreach var of local indicators {
    qui gen `var'_weight_final = `var'_w in 1
    qui replace `var'_weight_final = `var'_weight_final[_n-1] if missing(`var'_weight_final)
}

* 显示熵权计算结果
display "熵权计算结果："
display "================================================================================"
display "指标" _col(20) "熵值(E)" _col(35) "差异系数(D)" _col(50) "权重(W)" _col(65) "权重排名"
display "--------------------------------------------------------------------------------"

* 显示权重结果并计算排名
foreach var of local indicators {
    local e_val = `var'_e[1]
    local d_val = `var'_d[1]
    local w_val = `var'_w[1]

    * 计算权重排名
    local rank = 1
    foreach var2 of local indicators {
        local w_val2 = `var2'_w[1]
        if `w_val2' > `w_val' {
            local rank = `rank' + 1
        }
    }

    display "`var'" _col(20) %8.6f `e_val' _col(35) %8.6f `d_val' _col(50) %8.6f `w_val' _col(65) "`rank'"
}
display "================================================================================"

* 验证权重和为1
local weight_sum = 0
foreach var of local indicators {
    local weight_sum = `weight_sum' + `var'_w[1]
}
display "权重总和验证: " %8.6f `weight_sum' " (应为1.000000)"
display ""

* 权重解读
display "权重解读："
display "  - 权重越大，说明该指标在各企业间差异越大，对评价结果影响越大"
display "  - 权重越小，说明该指标在各企业间相对均衡"
display ""

/*------------------------------------------------------------------------------
第四部分：构建加权标准化矩阵
------------------------------------------------------------------------------*/

display ""
display "第四部分：构建加权标准化矩阵"
display "--------------------------------------------------------------------------------"
display "加权标准化: v_ij = x_ij* × W_j"
display ""

foreach var of local indicators {
    qui gen `var'_weighted = `var'_norm * `var'_w
    label variable `var'_weighted "`var'(加权标准化)"
}

* 显示加权标准化矩阵
display "加权标准化矩阵："
list company profit_weighted growth_weighted efficiency_weighted innovation_weighted risk_weighted satisfaction_weighted, clean noobs separator(0)

/*------------------------------------------------------------------------------
第五部分：确定正理想解和负理想解
------------------------------------------------------------------------------*/

display ""
display "第五部分：确定正理想解和负理想解"
display "--------------------------------------------------------------------------------"

* 计算正理想解（各指标最大值）和负理想解（各指标最小值）
foreach var of local indicators {
    qui egen `var'_max = max(`var'_weighted)
    qui egen `var'_min = min(`var'_weighted)
}

* 提取理想解值
foreach var of local indicators {
    local max_`var' = `var'_max[1]
    local min_`var' = `var'_min[1]
}

display "正理想解 (A+) 和负理想解 (A-)："
display "============================================================"
display "指标" _col(25) "正理想解(A+)" _col(45) "负理想解(A-)"
display "------------------------------------------------------------"
foreach var of local indicators {
    display "`var'" _col(25) %10.8f `max_`var'' _col(45) %10.8f `min_`var''
}
display "============================================================"
display ""
display "说明："
display "  - 正理想解(A+): 各指标的最优值（最大值）"
display "  - 负理想解(A-): 各指标的最劣值（最小值）"
display ""

/*------------------------------------------------------------------------------
第六部分：计算距离和相对贴近度
------------------------------------------------------------------------------*/

display ""
display "第六部分：计算距离和相对贴近度"
display "--------------------------------------------------------------------------------"

* 计算到正理想解的距离
display "6.1 计算到正理想解的距离 D+ = sqrt(Σ(v_ij - v_j+)²)"
gen dist_positive = 0
foreach var of local indicators {
    qui replace dist_positive = dist_positive + (`var'_weighted - `max_`var'')^2
}
qui replace dist_positive = sqrt(dist_positive)
label variable dist_positive "到正理想解距离"

* 计算到负理想解的距离
display "6.2 计算到负理想解的距离 D- = sqrt(Σ(v_ij - v_j-)²)"
gen dist_negative = 0
foreach var of local indicators {
    qui replace dist_negative = dist_negative + (`var'_weighted - `min_`var'')^2
}
qui replace dist_negative = sqrt(dist_negative)
label variable dist_negative "到负理想解距离"

* 计算相对贴近度
display "6.3 计算相对贴近度 C = D- / (D+ + D-)"
gen closeness = dist_negative / (dist_positive + dist_negative)
label variable closeness "相对贴近度"

* 计算排名
egen rank = rank(-closeness)
label variable rank "排名"

* 显示距离计算结果
display ""
display "距离计算结果："
display "======================================================================"
display "企业" _col(15) "D+(正理想解)" _col(35) "D-(负理想解)" _col(55) "C(贴近度)"
display "----------------------------------------------------------------------"
forvalues i = 1/`n_companies' {
    local comp = company[`i']
    local d_pos = dist_positive[`i']
    local d_neg = dist_negative[`i']
    local close = closeness[`i']
    display "`comp'" _col(15) %12.8f `d_pos' _col(35) %12.8f `d_neg' _col(55) %10.6f `close'
}
display "======================================================================"
display ""

/*------------------------------------------------------------------------------
第七部分：结果展示和分析
------------------------------------------------------------------------------*/

display ""
display "第七部分：结果展示和分析"
display "--------------------------------------------------------------------------------"

* 最终结果表
gen final_score = closeness * 100
label variable final_score "综合得分"

* 按排名排序
sort rank

display ""
display "企业管理综合评价最终结果："
display "=========================================================================================="
display "排名" _col(8) "企业名称" _col(20) "综合得分" _col(32) "相对贴近度" _col(46) "D+(正理想解)" _col(62) "D-(负理想解)"
display "------------------------------------------------------------------------------------------"

forvalues i = 1/`n_companies' {
    local company_name = company[`i']
    local score_val = final_score[`i']
    local closeness_val = closeness[`i']
    local pos_dist = dist_positive[`i']
    local neg_dist = dist_negative[`i']
    local rank_val = rank[`i']

    display %2.0f `rank_val' _col(8) "`company_name'" _col(20) %8.2f `score_val' _col(32) %10.6f `closeness_val' _col(46) %12.8f `pos_dist' _col(62) %12.8f `neg_dist'
}
display "=========================================================================================="

* 统计分析
display ""
display "统计分析："
qui summarize final_score, detail
display "  综合得分统计："
display "    - 最高分: " %6.2f r(max) " (排名第1)"
display "    - 最低分: " %6.2f r(min) " (排名第`n_companies')"
display "    - 平均分: " %6.2f r(mean)
display "    - 中位数: " %6.2f r(p50)
display "    - 标准差: " %6.2f r(sd)
display "    - 得分范围: " %6.2f r(max) - r(min)
display ""

* 分组分析
display "分组分析："
gen performance_level = ""
replace performance_level = "优秀" if rank <= 3
replace performance_level = "良好" if rank > 3 & rank <= 6
replace performance_level = "一般" if rank > 6

tab performance_level, missing
display ""

* 识别最佳和最差企业
qui summarize rank
local best_rank = r(min)
local worst_rank = r(max)

preserve
keep if rank == `best_rank'
local best_company = company[1]
local best_score = final_score[1]
restore

preserve
keep if rank == `worst_rank'
local worst_company = company[1]
local worst_score = final_score[1]
restore

display "关键发现："
display "  ✓ 最佳企业: `best_company' (得分: " %6.2f `best_score' ")"
display "  ✗ 最差企业: `worst_company' (得分: " %6.2f `worst_score' ")"
display "  △ 得分差距: " %6.2f `best_score' - `worst_score' " 分"
display ""

/*------------------------------------------------------------------------------
第八部分：敏感性分析（简化版）
------------------------------------------------------------------------------*/

display ""
display "第八部分：敏感性分析"
display "--------------------------------------------------------------------------------"
display "权重稳定性分析："
display ""

* 显示权重分布情况
display "各指标权重分布："
foreach var of local indicators {
    local w_val = `var'_w[1]
    display "  `var': " %8.6f `w_val'
}
display ""

* 计算权重的变异系数
* 先保存权重值到local宏
local weight_list = ""
foreach var of local indicators {
    local w_val = `var'_w[1]
    local weight_list = "`weight_list' `w_val'"
}

* 计算统计量
preserve
clear
set obs `n_indicators'
gen weight = .
local i = 1
foreach w of local weight_list {
    qui replace weight = `w' in `i'
    local i = `i' + 1
}
qui summarize weight
local weight_mean = r(mean)
local weight_sd = r(sd)
local weight_cv = `weight_sd' / `weight_mean'
restore

display "权重统计特征："
display "  - 平均权重: " %8.6f `weight_mean'
display "  - 标准差: " %8.6f `weight_sd'
display "  - 变异系数: " %8.6f `weight_cv'
display ""
display "说明："
display "  - 变异系数<0.15: 权重分布较均衡"
display "  - 变异系数>0.15: 存在权重差异较大的指标"
display "  - 本次分析变异系数为 " %6.4f `weight_cv'
if `weight_cv' < 0.15 {
    display "  → 权重分布相对均衡，各指标重要性相近"
}
else {
    display "  → 权重分布有差异，部分指标影响力较大"
}
display ""

/*------------------------------------------------------------------------------
第九部分：可视化分析
------------------------------------------------------------------------------*/

display ""
display "第九部分：可视化分析"
display "--------------------------------------------------------------------------------"

* 创建输出目录
capture mkdir "output/cases/figures"

* 确保数据按排名排序
sort rank

* 1. 综合得分排名图
display "生成图表1: 综合得分排名图..."
graph bar final_score, over(company, sort(rank) label(labsize(small))) ///
    title("企业管理综合评价得分排名", size(medium)) ///
    subtitle("基于熵权TOPSIS方法", size(small)) ///
    ytitle("综合得分") ///
    ylabel(0(10)100, labsize(small)) ///
    bar(1, fcolor(navy%70) lcolor(navy)) ///
    scheme(s2color) ///
    plotregion(margin(small)) ///
    graphregion(color(white)) ///
    note("注: 得分越高表示企业管理综合表现越好", size(vsmall))
graph export "output/cases/figures/enterprise_evaluation_ranking.png", as(png) width(1200) replace

* 2. 相对贴近度对比图
display "生成图表2: 相对贴近度对比图..."
graph bar (asis) closeness, over(company, sort(rank) label(labsize(small))) ///
    title("企业相对贴近度对比", size(medium)) ///
    subtitle("数值越大表示综合表现越好", size(small)) ///
    ytitle("相对贴近度") ///
    ylabel(0(0.1)1, labsize(small)) ///
    bar(1, fcolor(dkgreen%70) lcolor(dkgreen)) ///
    scheme(s2color) ///
    plotregion(margin(small)) ///
    graphregion(color(white)) ///
    note("注: 相对贴近度 = D- / (D+ + D-), 范围[0,1]", size(vsmall))
graph export "output/cases/figures/enterprise_closeness_comparison.png", as(png) width(1200) replace

* 3. 指标权重分布图
display "生成图表3: 指标权重分布图..."

* 先保存权重值到local宏
local profit_weight = profit_w[1]
local growth_weight = growth_w[1]
local efficiency_weight = efficiency_w[1]
local innovation_weight = innovation_w[1]
local risk_weight = risk_w[1]
local satisfaction_weight = satisfaction_w[1]

preserve
clear
set obs 6
gen str20 indicator = ""
gen weight = .

replace indicator = "盈利能力" in 1
replace weight = `profit_weight' in 1
replace indicator = "成长能力" in 2
replace weight = `growth_weight' in 2
replace indicator = "运营效率" in 3
replace weight = `efficiency_weight' in 3
replace indicator = "创新能力" in 4
replace weight = `innovation_weight' in 4
replace indicator = "风险控制" in 5
replace weight = `risk_weight' in 5
replace indicator = "客户满意度" in 6
replace weight = `satisfaction_weight' in 6

* 添加权重排名
egen weight_rank = rank(-weight)

graph bar (asis) weight, over(indicator, sort(weight_rank) label(labsize(small) angle(45))) ///
    title("评价指标权重分布", size(medium)) ///
    subtitle("基于熵权法计算（按权重从大到小排序）", size(small)) ///
    ytitle("权重值") ///
    ylabel(0(0.05)0.3, labsize(small) format(%4.2f)) ///
    bar(1, fcolor(maroon%70) lcolor(maroon)) ///
    scheme(s2color) ///
    plotregion(margin(small)) ///
    graphregion(color(white)) ///
    note("注: 权重越大说明该指标差异越大，对评价影响越大", size(vsmall))
graph export "output/cases/figures/indicator_weights.png", as(png) width(1200) replace
restore

* 4. 距离散点图
display "生成图表4: 距离散点图..."
* 添加颜色标记（按排名分组）
gen color_group = 1 if rank <= 3
replace color_group = 2 if rank > 3 & rank <= 6
replace color_group = 3 if rank > 6

twoway (scatter dist_negative dist_positive if color_group==1, ///
            mlabel(company) mlabsize(vsmall) mlabcolor(green) ///
            msymbol(O) mcolor(green%70) msize(medium)) ///
       (scatter dist_negative dist_positive if color_group==2, ///
            mlabel(company) mlabsize(vsmall) mlabcolor(blue) ///
            msymbol(O) mcolor(blue%70) msize(medium)) ///
       (scatter dist_negative dist_positive if color_group==3, ///
            mlabel(company) mlabsize(vsmall) mlabcolor(red) ///
            msymbol(O) mcolor(red%70) msize(medium)) ///
    , title("企业距离散点图", size(medium)) ///
    subtitle("理想解距离分析", size(small)) ///
    xtitle("到正理想解距离 (D+)") ///
    ytitle("到负理想解距离 (D-)") ///
    legend(order(1 "优秀(前3名)" 2 "良好(4-6名)" 3 "一般(7名后)") ///
           size(small) position(6) rows(1)) ///
    scheme(s2color) ///
    graphregion(color(white)) ///
    note("注: 理想企业应位于右下角（D+小，D-大）", size(vsmall))
graph export "output/cases/figures/distance_scatter.png", as(png) width(1200) replace

drop color_group

* 5. 各指标原始得分对比图（前5名企业）
display "生成图表5: 各指标原始得分对比图..."
preserve
keep if rank <= 5
sort rank

graph bar profit growth efficiency innovation risk satisfaction, ///
    over(company, sort(rank) label(labsize(small))) ///
    title("前5名企业各指标原始得分对比", size(medium)) ///
    subtitle("各维度表现分析", size(small)) ///
    legend(order(1 "盈利能力" 2 "成长能力" 3 "运营效率" ///
                 4 "创新能力" 5 "风险控制" 6 "客户满意度") ///
           size(vsmall) position(6) rows(2)) ///
    ylabel(0(20)100, labsize(small)) ///
    ytitle("得分") ///
    scheme(s2color) ///
    graphregion(color(white)) ///
    note("注: 显示排名前5的企业在各维度的原始得分", size(vsmall))
graph export "output/cases/figures/top5_indicators_comparison.png", as(png) width(1400) replace
restore

* 6. 综合得分与各指标相关性热力图（使用散点图矩阵）
display "生成图表6: 得分分布箱线图..."
graph box final_score, ///
    title("企业综合得分分布", size(medium)) ///
    subtitle("箱线图分析", size(small)) ///
    ytitle("综合得分") ///
    ylabel(, labsize(small)) ///
    marker(1, mcolor(navy%60)) ///
    box(1, fcolor(ltblue%50) lcolor(navy)) ///
    scheme(s2color) ///
    graphregion(color(white)) ///
    note("注: 箱线图显示得分的分布特征和离群值", size(vsmall))
graph export "output/cases/figures/score_distribution_box.png", as(png) width(800) replace

display "✓ 所有图表生成完成！"
display ""

/*------------------------------------------------------------------------------
第十部分：保存结果
------------------------------------------------------------------------------*/

display ""
display "第十部分：保存结果"
display "--------------------------------------------------------------------------------"

* 保存完整结果数据
save "data/cases/enterprise_evaluation_results.dta", replace
display "✓ 完整结果数据已保存: data/cases/enterprise_evaluation_results.dta"

* 保存结果到CSV文件
preserve
keep company rank final_score closeness dist_positive dist_negative performance_level
order company rank final_score closeness dist_positive dist_negative performance_level
sort rank
export delimited using "output/cases/enterprise_evaluation_results.csv", replace
display "✓ 评价结果已导出: output/cases/enterprise_evaluation_results.csv"
restore

* 保存权重信息
preserve
clear
input str20 indicator entropy difference_coef weight
"盈利能力" `profit_e[1]' `profit_d[1]' `profit_w[1]'
"成长能力" `growth_e[1]' `growth_d[1]' `growth_w[1]'
"运营效率" `efficiency_e[1]' `efficiency_d[1]' `efficiency_w[1]'
"创新能力" `innovation_e[1]' `innovation_d[1]' `innovation_w[1]'
"风险控制" `risk_e[1]' `risk_d[1]' `risk_w[1]'
"客户满意度" `satisfaction_e[1]' `satisfaction_d[1]' `satisfaction_w[1]'
end

* 添加权重排名
egen weight_rank = rank(-weight)
order indicator weight_rank weight entropy difference_coef
sort weight_rank

export delimited using "output/cases/indicator_weights.csv", replace
display "✓ 指标权重已导出: output/cases/indicator_weights.csv"
restore

* 保存详细分析报告（包含原始数据和所有中间结果）
preserve
keep company rank final_score closeness dist_positive dist_negative ///
     profit growth efficiency innovation risk satisfaction ///
     performance_level
order company rank final_score closeness performance_level ///
      profit growth efficiency innovation risk satisfaction ///
      dist_positive dist_negative
sort rank
export delimited using "output/cases/enterprise_evaluation_detailed_report.csv", replace
display "✓ 详细分析报告已导出: output/cases/enterprise_evaluation_detailed_report.csv"
restore

display ""

/*------------------------------------------------------------------------------
第十一部分：结果解释和管理建议
------------------------------------------------------------------------------*/

display ""
display "第十一部分：结果解释和管理建议"
display "--------------------------------------------------------------------------------"

display ""
display "================================================================================"
display "企业管理综合评价分析报告"
display "================================================================================"
display ""
display "一、评价方法概述"
display "  方法: 熵权TOPSIS方法"
display "  评价对象: `n_companies' 家企业"
display "  评价指标: `n_indicators' 个维度"
display "  数据来源: enterprise_evaluation.dta"
display ""

* 找出排名第一的企业
preserve
keep if rank == 1
local best_company = company[1]
local best_score = final_score[1]
local best_closeness = closeness[1]
local best_profit = profit[1]
local best_growth = growth[1]
local best_efficiency = efficiency[1]
local best_innovation = innovation[1]
local best_risk = risk[1]
local best_satisfaction = satisfaction[1]
restore

* 找出排名最后的企业
preserve
keep if rank == `n_companies'
local worst_company = company[1]
local worst_score = final_score[1]
local worst_closeness = closeness[1]
restore

display "二、主要发现"
display "  ✓ 最佳企业: `best_company'"
display "    - 综合得分: " %6.2f `best_score' " 分"
display "    - 相对贴近度: " %6.4f `best_closeness'
display "    - 各维度得分:"
display "      · 盈利能力: " %5.1f `best_profit'
display "      · 成长能力: " %5.1f `best_growth'
display "      · 运营效率: " %5.1f `best_efficiency'
display "      · 创新能力: " %5.1f `best_innovation'
display "      · 风险控制: " %5.1f `best_risk'
display "      · 客户满意度: " %5.1f `best_satisfaction'
display ""
display "  ✗ 最差企业: `worst_company'"
display "    - 综合得分: " %6.2f `worst_score' " 分"
display "    - 相对贴近度: " %6.4f `worst_closeness'
display "    - 与最佳企业差距: " %6.2f `best_score' - `worst_score' " 分"
display ""

* 权重分析
display "三、指标权重分析"
local max_weight = 0
local max_indicator = ""
local min_weight = 1
local min_indicator = ""

foreach var of local indicators {
    local current_weight = `var'_w[1]
    if `current_weight' > `max_weight' {
        local max_weight = `current_weight'
        local max_indicator = "`var'"
    }
    if `current_weight' < `min_weight' {
        local min_weight = `current_weight'
        local min_indicator = "`var'"
    }
}

display "  权重最高的指标: `max_indicator' (权重: " %6.4f `max_weight' ")"
display "    → 说明该指标在各企业间差异最大，对评价影响最大"
display ""
display "  权重最低的指标: `min_indicator' (权重: " %6.4f `min_weight' ")"
display "    → 说明该指标在各企业间相对均衡"
display ""
display "  完整权重排序:"
foreach var of local indicators {
    local w_val = `var'_w[1]
    local e_val = `var'_e[1]
    display "    `var'" _col(20) "权重: " %6.4f `w_val' _col(40) "熵值: " %6.4f `e_val'
}
display ""

* 分组统计
display "四、企业分组分析"
qui count if performance_level == "优秀"
local n_excellent = r(N)
qui count if performance_level == "良好"
local n_good = r(N)
qui count if performance_level == "一般"
local n_average = r(N)

display "  优秀企业 (前3名): `n_excellent' 家"
preserve
keep if performance_level == "优秀"
sort rank
forvalues i = 1/`=_N' {
    local comp = company[`i']
    local score = final_score[`i']
    display "    `i'. `comp' (得分: " %6.2f `score' ")"
}
restore

display ""
display "  良好企业 (4-6名): `n_good' 家"
preserve
keep if performance_level == "良好"
sort rank
forvalues i = 1/`=_N' {
    local comp = company[`i']
    local score = final_score[`i']
    local r = rank[`i']
    display "    `r'. `comp' (得分: " %6.2f `score' ")"
}
restore

display ""
display "  一般企业 (7名后): `n_average' 家"
preserve
keep if performance_level == "一般"
sort rank
forvalues i = 1/`=_N' {
    local comp = company[`i']
    local score = final_score[`i']
    local r = rank[`i']
    display "    `r'. `comp' (得分: " %6.2f `score' ")"
}
restore

display ""
display "五、管理建议"
display "  1. 对于优秀企业:"
display "     - 保持当前优势，继续强化核心竞争力"
display "     - 关注权重较高的指标，维持领先地位"
display "     - 可作为标杆企业，分享最佳实践"
display ""
display "  2. 对于良好企业:"
display "     - 分析与优秀企业的差距，找出改进方向"
display "     - 重点提升权重较高的指标表现"
display "     - 学习优秀企业的成功经验"
display ""
display "  3. 对于一般企业:"
display "     - 全面诊断各项指标，制定改进计划"
display "     - 优先改善短板指标"
display "     - 寻求外部支持和资源"
display ""

display "六、方法说明与局限性"
display "  优势:"
display "    ✓ 客观性强: 权重由数据驱动，避免主观偏见"
display "    ✓ 信息利用充分: 综合考虑所有指标和样本"
display "    ✓ 结果直观: 相对贴近度易于理解和比较"
display ""
display "  局限性:"
display "    ⚠ 数据依赖: 结果质量取决于数据质量"
display "    ⚠ 忽略专家经验: 完全客观可能忽略战略重点"
display "    ⚠ 样本敏感: 样本变化会影响权重和排名"
display ""
display "  建议:"
display "    → 定期更新数据，保持评价时效性"
display "    → 结合定性分析，全面理解企业表现"
display "    → 进行敏感性分析，验证结果稳定性"
display "    → 必要时可结合主观权重，体现战略导向"
display ""

display "================================================================================"
display "分析完成！"
display "================================================================================"
display ""
display "输出文件："
display "  1. 完整结果数据: data/cases/enterprise_evaluation_results.dta"
display "  2. 评价结果CSV: output/cases/enterprise_evaluation_results.csv"
display "  3. 指标权重CSV: output/cases/indicator_weights.csv"
display "  4. 详细报告CSV: output/cases/enterprise_evaluation_detailed_report.csv"
display "  5. 图表文件: output/cases/figures/*.png (共6张图表)"
display "  6. 日志文件: output/cases/case10_entropy_topsis_evaluation.log"
display ""

* 清理临时变量
foreach var of local indicators {
    capture drop `var'_norm `var'_weight `var'_e `var'_d `var'_w `var'_weight_final
    capture drop `var'_weighted `var'_max `var'_min
}

display "结束时间: " c(current_date) " " c(current_time)
display "程序执行完毕。"
display ""

* 关闭日志
log close
